from django.core.management.base import BaseCommand
from django.utils.text import slugify
from blog.models import Post


class Command(BaseCommand):
    help = '修复数据库中 slug 为空的文章'

    def handle(self, *args, **options):
        # 获取所有 slug 为空的文章
        empty_slug_posts = Post.objects.filter(slug__isnull=True) | Post.objects.filter(slug='')
        count = empty_slug_posts.count()

        if count == 0:
            self.stdout.write(self.style.SUCCESS('没有找到 slug 为空的文章'))
            return

        self.stdout.write(f'找到 {count} 篇 slug 为空的文章，开始修复...')

        for post in empty_slug_posts:
            # 生成基础 slug
            base_slug = slugify(post.title)
            if not base_slug:
                base_slug = f'post-{post.id}'

            # 确保 slug 唯一
            slug = base_slug
            counter = 1
            while Post.objects.filter(
                    slug=slug,
                    publish_date__year=post.publish_date.year,
                    publish_date__month=post.publish_date.month,
                    publish_date__day=post.publish_date.day
            ).exclude(id=post.id).exists():
                slug = f'{base_slug}-{counter}'
                counter += 1

            post.slug = slug
            post.save(update_fields=['slug'])
            self.stdout.write(f'已修复文章 ID {post.id}: "{post.title}" -> slug="{slug}"')

        self.stdout.write(self.style.SUCCESS(f'成功修复 {count} 篇文章的 slug'))

